#include <iostream>
#include "compile_run.hpp"
#include "../comm/httplib.h"

using namespace ns_compile_run;
using namespace httplib;

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        std::cerr << "Usage:\n\t" << argv[0] << " port" << std::endl;
        return -1;
    }
    Server svr;
    // 用来给oj_server检测网络是否通畅
    svr.Get("/check_net", [](const Request &req, Response &rep)
            { rep.set_content("ok", "text/html;charset=utf-8"); });
    // 注册POST方法
    svr.Post("/compile_run", [](const Request &req, Response &rep)
             {
        std::string in_json = req.body;
        std::string out_json;
        CompileRun::Start(in_json, out_json);
        rep.set_content(out_json, "application/json;charset=utf-8"); });

    LOG(INFO, "begin listen");
    svr.listen("0.0.0.0", atoi(argv[1]));
    // Json::Value root;
    // root["code"] = "#include <iostream>\nint main()\n{\n\tstd::cout << \"hello world\" << std::endl;\n\treturn 0;\n}";
    // // root["code"] = "#include <iostream>\nint main()\n{\n\twhile(1);\n\treturn 0;\n}";
    // // root["code"] = "#include <iostream>\nint main()\n{\n\twhile(1)int *p = new int[1024*1024];\n\treturn 0;\n}";
    // root["input"] = 0;
    // root["cpu_limit"] = 1;
    // int mem_limit = 1024 * 1024 * 30;
    // root["mem_limit"] = mem_limit;
    // Json::FastWriter writer;
    // std::string in_json = writer.write(root);
    // std::cout << in_json << std::endl;
    // std::string out_json;
    // CompileRun::Start(in_json, out_json);
    // std::cout << out_json << std::endl;
    // Json::Value out_value;
    // Json::Reader reader;
    // reader.parse(out_json, out_value);

    // std::cout << "status: " << out_value["status"] << std::endl;
    // std::cout << "reason: " << out_value["reason"] << std::endl;
    // if (out_value["status"].asInt() == 0)
    // {
    //     std::cout << "stdout: " << out_value["stdout"] << std::endl;
    //     std::cout << "stderr: " << out_value["stderr"] << std::endl;
    // }

    return 0;
}
